<?php
/**
 * Created by PhpStorm.
 * User: 96151
 * Date: 2018/12/5
 * Time: 14:44
 */
namespace app\common\redis;
use app\common\service\ElkLog;

/**
 * Redis锁
 * Class LockRedis
 */
class LockRedis extends RedisModel
{
    public function lock( $key, $expire = 5 )
    {
        if(!$key) {
            return false;
        }

        $i = 1000 * $expire;

        do {
            if( $acquired = ( $this->Setnx( time(),"Lock:{$key}" ) ) ) { // 如果redis不存在，则成功
                ElkLog::write( array( "message"=> "LockRedis_lock", "key" => "Lock:{$key}") );
                $this->Expire( $expire, $key );
                break;
            }
            $i--;

            if ( $i < 0 ){
                $this->release( $key );
            }

            usleep( 1000 );

        } while (true);

        return true;
    }

    //释放锁
    public function release( $key )
    {
        ElkLog::write( array( "message"=> "LockRedis_lock_release", "key" => "Lock:{$key}") );
        if(!$key) {
            return false;
        }

        $this->Delete("Lock:{$key}");
        return true;
    }
}